﻿using Client;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StationClient
{
    public partial class FormLabelCheck : Form
    {
        private readonly FormStation _formSta = null;//上一个界面
        private readonly STATION _sta = null;//当前工位信息
        //private PROCESS _process = null;//保存过程信息

        private Device_Data _deviceData = null;//mac device

        public FormLabelCheck(FormStation formSta, STATION sta)
        {
            _sta = sta;
            _formSta = formSta;
            InitializeComponent();

            TextBoxFocus(0);
        }

        private void TextBoxMAC_KeyPress(object sender, KeyPressEventArgs e)
        {
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                if (CheckMac(out string msg))
                {

                    TextBoxFocus(1);
                }
                else
                {
                    SetResult(false, msg);
                    TextBoxFocus(0);
                }
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'f')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'F')
                || (e.KeyChar >= '0' && e.KeyChar <= '9')
                || (e.KeyChar == 8))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                MessageBox.Show("只能输入数字和A-F");
                e.Handled = true;
            }
        }

        private bool CheckMac(out string msg)
        {
            string productMac = this.textBoxMAC.Text.Trim();

            msg = string.Empty;

            if (string.IsNullOrEmpty(productMac))
            {
                msg = "MAC地址为空";
                return false;
            }

            //判断MAC地址是否12位
            if (productMac.Length != 12)
            {
                msg = "MAC地址不为12位";
                return false;
            }

            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();

            deviceW.MACAddr = this.textBoxMAC.Text.Trim();

            var selectDecive = MethodWcf.SelectDeviceDataClient(deviceW);

            if (selectDecive.result)
            {
                _deviceData = selectDecive.value[0];
            }
            else
            {
                msg = "未能找到MAC对应的信息，请查询输入是否正确";
                return false;
            }

            return true;

        }

        private void TextBoxFocus(int sort)
        {
            this.textBoxMAC.Enabled = false;
            this.textBoxCode.Enabled = false;
            this.textBoxSn.Enabled = false;
            if (sort == 0)
            {
                //输入MAC
                this.textBoxMAC.Enabled = true;
                this.textBoxMAC.Clear();
                this.textBoxMAC.Focus();
            }
            else if (sort == 1)
            {
                this.textBoxCode.Enabled = true;
                this.textBoxCode.Clear();
                this.textBoxCode.Focus();
            }
            else if (sort == 2)
            {
                this.textBoxSn.Enabled = true;
                this.textBoxSn.Clear();
                this.textBoxSn.Focus();
            }
        }

        private void TextBoxCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (_deviceData == null) return;

            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                string codeStr = this.textBoxCode.Text;

                if (codeStr.Contains(_deviceData.MACAddr)
                    || codeStr.Contains(_deviceData.DeviceSerialNumber)
                    || (_deviceData.SN != null && codeStr.Contains(_deviceData.SN))
                    || (_deviceData.XPON_SN != null && codeStr.Contains(_deviceData.XPON_SN))
                    )
                {
                    TextBoxFocus(2);
                }
                else
                {
                    SetResult(false, "检查失败");
                    TextBoxFocus(0);
                    _deviceData = null;
                }
            }
        }

        private void TextBoxSn_KeyPress(object sender, KeyPressEventArgs e)
        {
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                string codeStr = this.textBoxSn.Text.Trim();

                if (codeStr.Contains(_deviceData.MACAddr)
                    || codeStr.Contains(_deviceData.DeviceSerialNumber)
                    || (_deviceData.SN != null && codeStr.Contains(_deviceData.SN))
                    || (_deviceData.XPON_SN != null && codeStr.Contains(_deviceData.XPON_SN))
                    )
                {
                    SetResult(true, null);
                }
                else
                {
                    SetResult(false, "检查失败");
                }

                TextBoxFocus(0);
                _deviceData = null;
            }
        }

        private void SetResult(bool result,string msg)
        {
            if (this.labelResult.InvokeRequired)
            {
                Action<bool, string> d = new Action<bool, string>(SetResult);
                Invoke(d, result, msg);
            }
            else
            {
                SaveProcess(result);

                if (result)
                {
                    this.labelResult.ForeColor = Color.Green;
                    this.labelResult.Text = "PASS";
                }
                else
                {
                    this.labelResult.ForeColor = Color.Red;
                    this.labelResult.Text = "FAIL_" + msg;
                }
            }
        }

        private void SaveProcess(bool result)
        {
            PROCESS processI = new PROCESS();
            processI.SetUpdate();

            if (result) processI.TEST_RESULT = "Y";
            else processI.TEST_RESULT = "N";
            processI.MAC = _deviceData.MACAddr;
            processI.LINE_ID = _sta.LINE_ID;
            processI.NODE_ID = _sta.NODE_ID;
            processI.STATION_ID = _sta.ID;
            processI.END_TIME = DateTime.Now;
            processI.START_TIME = DateTime.Now.AddSeconds(-10);
            processI.WORKER_ID = _sta.WORKER_ID;
            processI.WORKER_NAME = _sta.WORKER_NAME;
            processI.FLOW_ID = _sta.FLOW_ID;

            MethodWcf.InsertProcessClient(processI);
        }

        private List<Device_Data> devices = new List<Device_Data>();//存储BOXSN对应的DeviceData
        private int checks = 0;//扫描的数量

        private void TextBoxEnterBoxSn_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar=='\r' || e.KeyChar == '\n')
            {
                string boxSn = this.textBoxEnterBoxSn.Text.Trim();

                BOX_MODEM boxW = new BOX_MODEM();
                boxW.SetWhere();
                boxW.BOX_NO = boxSn;

                var selectBox = MethodWcf.SelectBoxModemClient(boxW);

                if (selectBox.result)
                {
                    //查找Device
                    BOX_MODEM boxModem = selectBox.value[0];

                    string identify = " IN('";

                    for (int j = 1; j <= boxModem.COUNT; j++)
                    {
                        switch (j)
                        {
                            case 1:
                                identify += boxModem.DSNum_1 + "','";
                                break;
                            case 2:
                                identify += boxModem.DSNum_2 + "','";
                                break;
                            case 3:
                                identify += boxModem.DSNum_3 + "','";
                                break;
                            case 4:
                                identify += boxModem.DSNum_4 + "','";
                                break;
                            case 5:
                                identify += boxModem.DSNum_5 + "','";
                                break;
                            case 6:
                                identify += boxModem.DSNum_6 + "','";
                                break;
                            case 7:
                                identify += boxModem.DSNum_7 + "','";
                                break;
                            case 8:
                                identify += boxModem.DSNum_8 + "','";
                                break;
                            case 9:
                                identify += boxModem.DSNum_9 + "','";
                                break;
                            case 10:
                                identify += boxModem.DSNum_10 + "','";
                                break;
                            case 11:
                                identify += boxModem.DSNum_11 + "','";
                                break;
                            case 12:
                                identify += boxModem.DSNum_12 + "','";
                                break;
                            case 13:
                                identify += boxModem.DSNum_13 + "','";
                                break;
                            case 14:
                                identify += boxModem.DSNum_14 + "','";
                                break;
                            case 15:
                                identify += boxModem.DSNum_15 + "','";
                                break;
                            case 16:
                                identify += boxModem.DSNum_16 + "','";
                                break;
                            case 17:
                                identify += boxModem.DSNum_17 + "','";
                                break;
                            case 18:
                                identify += boxModem.DSNum_18 + "','";
                                break;
                            case 19:
                                identify += boxModem.DSNum_19 + "','";
                                break;
                            case 20:
                                identify += boxModem.DSNum_20 + "','";
                                break;
                            default:
                                break;
                        }
                    }

                    identify = identify.TrimEnd(',', '\'') + "')";

                    //查询identify对应的数据
                    Device_Data deviceDataW = new Device_Data();
                    deviceDataW.SetWhere(string.Format("DeviceSerialNumber {0} ORDER BY SN", identify));

                    var selectDeviceData = MethodWcf.SelectDeviceDataClient(deviceDataW);
                    if (selectDeviceData.result == false)
                    {
                        MessageBox.Show("查询产品信息错误");
                        return;
                    }

                    devices = selectDeviceData.value;

                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, $"箱号[{boxSn}]对应的数据量为{boxModem.COUNT}");

                    this.textBoxTarget.Focus();
                    this.textBoxEnterBoxSn.ReadOnly = true;
                }
                else
                {
                    this.textBoxEnterBoxSn.Clear();
                    this.textBoxEnterBoxSn.Focus();
                }
            }
        }

        private void TextBoxTarget_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' || e.KeyChar == '\n')
            {
                string target = this.textBoxTarget.Text.Trim();

                var device = (from d in devices
                              where d.DeviceSerialNumber == target || d.SN == target || d.LightModuleSN == target || d.MACAddr == target
                              select d).FirstOrDefault();

                if (device != null)
                {
                    this.labelCheckState.Text = "PASS";
                    this.labelCheckState.ForeColor = Color.Green;

                    if (device.ProductCode != "CHECKED")
                    {
                        device.ProductCode = "CHECKED";
                        checks += 1;
                    }

                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, $"Target[{target}]在箱号中，当前已经检查的产品数量为[{checks}]");
                }
                else
                {
                    this.labelCheckState.Text = "FAIL";
                    this.labelCheckState.ForeColor = Color.Red;
                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, $"Target[{target}]不在箱号中");

                }

                this.textBoxTarget.Clear();
                this.textBoxTarget.Focus();

                if (checks == devices.Count)
                {
                    this.textBoxEnterBoxSn.Focus();
                }
            }
        }

        //private void TextBoxEnterBoxSn_MouseClick(object sender, MouseEventArgs e)
        //{

        //}

        private void TextBoxEnterBoxSn_Enter(object sender, EventArgs e)
        {
            //初始化数据
            this.textBoxEnterBoxSn.Clear();
            this.textBoxTarget.Clear();
            this.richTextBoxMsg.Clear();
            checks = 0;
            this.textBoxEnterBoxSn.ReadOnly = false;
            devices.Clear();
        }
    }
}
